package sz.szsmk.citizencard.ui.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.appcompat.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import java.io.File;

import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.PermissionUtil;
import sz.szsmk.citizencard.util.zxyh.DeviceUtils;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;

/**
 * Created by hyt on 2019/4/25.
 */
public class SelectImageActivity extends AppCompatActivity implements View.OnClickListener  {

   Dialog dialog;
   View inflate;

    TextView tv_getImage;
    TextView tv_takephoto;
    TextView tv_cancle;

    // 拍照临时图片
    String mTempPhotoPath ;

    public final static int  GALLERY_REQUEST_CODE = 0;    // 相册选图标记
    public final static int CAMERA_REQUEST_CODE = 1;     // 相机拍照标记


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE); //去除这个Activity的标题栏
        //空白activity
        setContentView(R.layout.activity_selectimg);
        mTempPhotoPath = Constant.CACHEPATH_IMAGE + "photo.jpeg";


        dialog = new Dialog(this, R.style.bottomDialogStyle);
        inflate = LayoutInflater.from(this).inflate(R.layout.dialog_selectimg, null);
        //初始化控件
        tv_getImage = inflate.findViewById(R.id.tv_getImage);
        tv_takephoto = inflate.findViewById(R.id.tv_takephoto);
        tv_cancle = inflate.findViewById(R.id.tv_cancle) ;
        //将布局设置给Dialog
        dialog.setContentView(inflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = dialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity( Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = MATCH_PARENT;
        //将属性设置给窗体
        dialogWindow.setAttributes(lp);
        dialog.setOnDismissListener(dialog -> finish());
        tv_cancle.setOnClickListener(v->{dialog.dismiss();finish();});
        dialog.show();//显示对话框

        initViewEvent();
    }

    private void initViewEvent(){
        inflate.setOnClickListener(v ->{
            dialog.dismiss();
        } );

        dialog.setOnDismissListener(v->{
            dialog.dismiss();
        });

        tv_getImage.setOnClickListener(this);
        tv_takephoto.setOnClickListener(this);

    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_getImage) {
            pickFromGalleryInternal();
        } else if (id == R.id.tv_takephoto) {
            takePhotoInternal();
        }
    }

    //拍照
    //拍照会在指定的目录下 生成一个图片文件 然后把地址传入Intent 中
    //拍照后 直接操作这个文件
    //Android7.0 操作文件需要 google 收起了对私有目录的访问  需要配置一些内容
    //具体配置：http://blog.csdn.net/zz110753/article/details/60877594
    private void takePhotoInternal() {
        File newfile = new File(mTempPhotoPath);
        try {
            File path = new File(Constant.CACHEPATH_IMAGE);
            if (!path.exists()) {
                path.mkdirs();
            }
            newfile.createNewFile();
        } catch (Exception e) {
            e.printStackTrace();
        }

        Uri outputFileUri = FileProvider.getUriForFile(this,
                getPackageName()+".fileProvider",
                newfile
        );
        Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //添加权限
        takeIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        //下面这句指定调用相机拍照后的照片存储的路径
        takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
        startActivityForResult(takeIntent, CAMERA_REQUEST_CODE);
    }


    //打开相册
    private void pickFromGalleryInternal() {
        Intent pickIntent = new Intent(Intent.ACTION_PICK, null);
        // 如果限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型"
        pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(pickIntent, GALLERY_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if ((requestCode == GALLERY_REQUEST_CODE || requestCode == CAMERA_REQUEST_CODE) && resultCode == RESULT_OK) {
            Intent intent = new Intent();
            String path = null;
            switch(requestCode) {
                case CAMERA_REQUEST_CODE:   // 调用相机拍照
                    path = mTempPhotoPath ;
                break;
                case GALLERY_REQUEST_CODE:  // 直接从相册获取
                    path = DeviceUtils.uri2File(this ,data.getData()).getAbsolutePath();
                break;
            }
            intent.putExtra("imagePath",path);
            setResult(100,intent);
            dialog.dismiss();
            finish();
        }
    }
}
